package dao;

import util.ConfigManager;
import java.sql.*;

public class BaseDao {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    public Connection getConn() {
        return conn;
    }

    public PreparedStatement getPs() {
        return ps;
    }

    public ResultSet getRs() {
        return rs;
    }

    public  boolean getConnection(){
        boolean flag = false;
        String driver = ConfigManager.getInstance().getValue("driver");
        String url = ConfigManager.getInstance().getValue("url");
        String username = ConfigManager.getInstance().getValue("username");
        String password = ConfigManager.getInstance().getValue("password");
        //加载驱动
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username,password);
            flag = true;

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } return flag;
    }

    /**
     * 查询操作
     * @param sql
     * @param params
     * @return
     */
    public  ResultSet executeSelect(String sql,Object[] params){
        if(getConnection()){
            try {
                ps = conn.prepareStatement(sql);
                if(params!=null){
                    for (int i = 0; i <params.length ; i++) {
                        ps.setObject(i+1,params[i]);
                    }
                }
                rs = ps.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return  rs;
    }

    public  int executeUpdateRows(String sql,Object[] params){
        int rows = 0;
        if(getConnection()){
            try {
                ps = conn.prepareStatement(sql);
                if(params!=null){
                    for (int i = 0; i <params.length ; i++) {
                        ps.setObject(i+1,params[i]);
                    }
                }
                rows = ps.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return  rows;
    }
    /**
     *  关闭连接
     */
    public void closeAll(){
        try {
            if(rs!=null){
                rs.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
